//
//  YKTopicsController.m
//  baisi
//
//  Created by 吴高烽 on 16/10/7.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKTopicsController.h"
#import "YKCommetnViewController.h"
#import <AFNetworking.h>
#import <SVProgressHUD.h>
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "YKTopic.h"
#import <MJExtension.h>
#import "YKTopicCell.h"
#import "YKNewViewController.h"
//@class YKNewViewController ;
@interface YKTopicsController ()
@property (nonatomic ,strong)NSMutableArray *topics;
/** 当前页码 */
@property (nonatomic,assign)NSInteger page;
/** 当加载下一页数据时需要这个参数 */
@property (nonatomic,copy)NSString *maxtime ;
/** 上一次的请求参数 */
@property (nonatomic ,strong)NSDictionary *params;
/** 上一次点击的TabBar的索引 */
@property (nonatomic,assign)NSUInteger lastSelectIndex;

@end
static NSString * const YKTopicCellID  = @"topCellID";
@implementation YKTopicsController
/*-(NSString *)type{
    return  nil ;
    
}*/
-(NSMutableArray *)topics{
    if (!_topics) {
        _topics = [NSMutableArray array];
    }
    return _topics ;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //  设置tableView的约束
    [self setupTableView];
    //    [self loadNewData];
}
-(void)setupTableView{
    // 设置内边距
    CGFloat bottom = self.tabBarController.tabBar.height ;
    CGFloat top = YKTitlesViewH + YKTitlesViewY ;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    //    设置滚动条的内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset ;
    // 设置刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // 自动改变下拉刷新控件的透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES ;
    // 开始下拉刷新 会自动调用loadNewData 方法
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YKTopicCell class]) bundle:nil] forCellReuseIdentifier:YKTopicCellID];
//    注册刷新的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarDidSelected) name:YKTbaBarDidSelectNotification object:nil];
    
}
-(void)tabBarDidSelected{
    if (self.lastSelectIndex == self.tabBarController.selectedIndex && [self.view isShowOnKeyWindow]) {
//         开始刷新tableView
        [self.tableView.mj_header beginRefreshing];
    }
    self.lastSelectIndex = self.tabBarController.selectedIndex ;
    
}
-(void)loadNewData{
    // 结束上拉
    [self.tableView.mj_footer endRefreshing];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    //params[@"maxtime"]=@"";
    self.params = params ;
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    //    [SVProgressHUD show];
    [[AFHTTPSessionManager manager]GET: baisiURL parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if (self.params !=params) {
            return ;
        }
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        [SVProgressHUD dismiss];
        YKLog(@"%@",[responseObject mj_JSONString]);
        NSArray *topics = [YKTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:topics];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        self.page = 0 ;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败"];
        [self.tableView.mj_header endRefreshing];
    }];
    
}
-(NSString*)a{
    return  [self.parentViewController isKindOfClass:[YKNewViewController class]] ? @"newlist" : @"list" ;
}
-(void)loadMoreData{
    // 结束下拉
    [self.tableView.mj_header endRefreshing];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    NSInteger page = self.page + 1 ;
    params[@"page"] = @(page);
    params[@"maxtime"]=self.maxtime;
    self.params = params ;
    
    [[AFHTTPSessionManager manager]GET: baisiURL parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        if (self.params !=params) {
            return ;
        }
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        //[SVProgressHUD dismiss];
        //YKLog(@"%@",[responseObject mj_JSONString]);
        NSArray *topics = [YKTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:topics];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
        self.page = page ;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.params != params) return;
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // return 10;
    self.tableView.mj_footer.hidden = (self.topics.count == 0) ;
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YKTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:YKTopicCellID];
    cell.topic = self.topics[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    YKTopic *topc = self.topics[indexPath.row];
    return topc.cellHeight ;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YKCommetnViewController *commentVC = [[YKCommetnViewController alloc]init];
    commentVC.topic = self.topics[indexPath.row];
    [self.navigationController pushViewController:commentVC animated:YES];
   // [self.navigationController presentViewController:commentVC animated:YES completion:nil];
}
@end
